/**
 * Copyright (c) 2010-2011 julewa.com.  
 * All rights reserved. 
 * 
 * @author Huang Benhua
 * @date 2011-2-20
 * 
**/
package com.julewa;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.julewa.freemarker.FreemarkerManager;
import com.julewa.loading.PreInterceptor;
import com.julewa.loading.SpringLoader;
import com.julewa.loading.StrutsLoader;
import com.julewa.loading.SystemUtils;
/**
 * 
 * @author huang benhua
 * 
 */
public final class Controller implements Filter{
	private SpringLoader springloader = null;
	private StrutsLoader strutsloader = null;
	private PreInterceptor interceptor = null;
	private String encoding = "UTF-8";
	public Controller(){
		SystemUtils.initialize();
		encoding = SystemUtils.getProperty("system.encoding");
	}
	public void init(FilterConfig conf) throws ServletException{
		FreemarkerManager freemarker = new FreemarkerManager(StrutsLoader.class);
		strutsloader = new StrutsLoader(freemarker.load("struts"));
		springloader = new SpringLoader(freemarker.load("spring"), freemarker.load("properties"));
		springloader.load(conf.getServletContext());
		strutsloader.load(conf);
		interceptor = SpringLoader.getInstance(PreInterceptor.class);
	}
	@SuppressWarnings("finally")
	public void doFilter(ServletRequest request,ServletResponse response,
			FilterChain chain)throws IOException,ServletException{
		if(request instanceof HttpServletRequest){
			request.setCharacterEncoding(encoding);
			if(interceptor.before((HttpServletRequest)request, (HttpServletResponse)response))try{
	        	strutsloader.doFilter(request, response, chain);
	        	}finally{
	        		interceptor.after((HttpServletRequest)request, (HttpServletResponse)response);
	        		return;
	        }else{
	           // HttpServletResponse resp=(HttpServletResponse)response;
	            //resp.setHeader("Pragma", "No-cache");
	            //resp.setDateHeader("Expires", 10000);
	            //resp.setHeader("Cache-Control", "no-cache");
	        }
		}
		chain.doFilter(request, response);
    }
	public void destroy(){
		strutsloader.close();
		springloader.close();
	}
}
